package com.lc.advertising.ui.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapException;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.Polyline;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviRouteNotifyData;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapRestrictionInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.advertising.R;
import com.lc.advertising.app.AppActivity;
import com.lc.advertising.http.glide.GlideApp;
import com.lc.advertising.http.request.OrderQuerenApi;
import com.lc.advertising.http.request.QiangSaveApi;
import com.lc.advertising.http.request.QiangShowApi;
import com.lc.advertising.http.response.QiangShowBean;
import com.lc.advertising.http.response.RegisterBean;
import com.lc.advertising.other.IntentKey;
import com.lc.advertising.util.SPUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GrabbingDetailsActivity extends AppActivity implements AMapNaviListener, AMap.OnPolylineClickListener {


    @BindView(R.id.bottom_sheet)
    RelativeLayout bottomSheet;
    @BindView(R.id.cl_chouti)
    CoordinatorLayout clChouti;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.staute)
    TextView staute;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.tv_dance)
    TextView tvDance;
    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.btn_service)
    Button btnService;
    @BindView(R.id.btn_destination)
    Button btnDestination;
    @BindView(R.id.btn_qiangdan)
    Button btnQiangdan;
    @BindView(R.id.route_map)
    MapView mRouteMapView;

    private String longitude;
    private String latitude;
    private BottomSheetBehavior<View> behavior;
    private String id;
    private String phone;
    private LocationSource.OnLocationChangedListener mListener = null;//定位监听器
    private static final String TAG = "GrabbingDetailsActivity";


    /**
     * 导航对象(单例)
     */
    private AMapNavi mAMapNavi;
    private AMap mAmap;
    /**
     * 地图对象
     */

    private Marker mStartMarker;
    private Marker mEndMarker;
    private NaviLatLng endLatlng ;
    private NaviLatLng startLatlng;
    private List<NaviLatLng> startList = new ArrayList<NaviLatLng>();
    /**
     * 途径点坐标集合
     */
    private List<NaviLatLng> wayList = new ArrayList<NaviLatLng>();
    /**
     * 终点坐标集合［建议就一个终点］
     */
    private List<NaviLatLng> endList = new ArrayList<NaviLatLng>();
    /**
     * 保存当前算好的路线
     */
    private SparseArray<RouteOverLay> routeOverlays = new SparseArray<RouteOverLay>();

    /**
     * 当前用户选中的路线，在下个页面进行导航
     */
    private int routeIndex;
    /**
     * 路线的权值，重合路线情况下，权值高的路线会覆盖权值低的路线
     **/
    private int zindex = 1;
    /**
     * 路线计算成功标志位
     */
    private boolean calculateSuccess = false;
    private boolean chooseRouteSuccess = false;
    // 是否需要跟随定位
    private boolean isNeedFollow = true;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_grabbingdetails;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        mRouteMapView.onCreate(savedInstanceState);
        mAmap = mRouteMapView.getMap();
        mAmap.getUiSettings().setZoomControlsEnabled(false);
        mAmap.setOnPolylineClickListener(this);
        mAmap.setMapType(AMap.MAP_TYPE_NAVI);
        // 初始化Marker添加到地图
//        mStartMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.start))));
//        mEndMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.end))));

        try {
            mAMapNavi = AMapNavi.getInstance(getApplicationContext());
        } catch (AMapException e) {
            e.printStackTrace();
        }
        mAMapNavi.addAMapNaviListener(this);
        mAmap.setOnPolylineClickListener(this);
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        startLatlng= new NaviLatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));//起点，39.942295,116.335891
//        mStartMarker.setPosition(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
        startList.clear();
        startList.add(startLatlng);
        mRouteMapView.post(new Runnable() {
            @Override
            public void run() {
        mAmap.moveCamera(CameraUpdateFactory.zoomTo(14));
        //将地图移动到定位点
        mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude))));
            }
        });


        id = getIntent().getStringExtra("id");
        qiang_show();
        behavior = BottomSheetBehavior.from(bottomSheet);

        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @BottomSheetBehavior.State int newState) {
                String state = "null";
                switch (newState) {
                    case 1:
                        state = "STATE_DRAGGING";//过渡状态此时用户正在向上或者向下拖动bottom sheet
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                    case 2:
                        state = "STATE_SETTLING"; // 视图从脱离手指自由滑动到最终停下的这一小段时间
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                    case 3:
                        state = "STATE_EXPANDED"; //处于完全展开的状态
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                    case 4:
                        state = "STATE_COLLAPSED"; //默认的折叠状态

                        break;
                    case 5:
                        state = "STATE_HIDDEN"; //下滑动完全隐藏 bottom sheet
                        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                        break;
                }

            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//                Log.d("BottomSheetDemo", "slideOffset:" + slideOffset);
            }
        });

    }

    private void qiang_show() {
        EasyHttp.post(this)
                .api(new QiangShowApi()
                        .setUid(SPUtil.get(this, IntentKey.UID, "")).setJingdu(longitude).setWeidu(latitude).setId(id))
                .request(new HttpCallback<QiangShowBean>(this) {

                    @Override
                    public void onSucceed(QiangShowBean data) {
//
                        if (data.getCode() == 200) {
                            time.setText(data.getQiangdan().getCreate_time());
                            tvStart.setText(data.getQiangdan().getBegin_place());
                            tvEnd.setText(data.getQiangdan().getEnd_place());
                            staute.setText("状态：" + data.getQiangdan().getZhuangtai());
                            tvDance.setText(data.getQiangdan().getJulis());
                            tvName.setText(data.getQiangdan().getMember_nickname());
                            GlideApp.with(getActivity())
                                    .load(IntentKey.URL + data.getQiangdan().getMember_headimg())
                                    .placeholder(R.mipmap.img_head)
                                    .error(R.mipmap.img_head)
                                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                    .into(imgHead);

                            tvPrice.setText(data.getQiangdan().getPrice());
                            phone = data.getQiangdan().getMember_mobile();
                            tvPhone.setText(phone);
                            if (data.getQiangdan().getCheckinfo() == 0) {
                                btnQiangdan.setVisibility(View.VISIBLE);
                                btnService.setVisibility(View.GONE);
                                btnDestination.setVisibility(View.GONE);
                            } else {
                                btnQiangdan.setVisibility(View.GONE);
                                btnService.setVisibility(View.VISIBLE);
                                btnDestination.setVisibility(View.VISIBLE);
                            }

                            endLatlng=   new NaviLatLng(Double.parseDouble(data.getQiangdan().getWeidu()), Double.parseDouble(data.getQiangdan().getJingdu()));
//                            mEndMarker.setPosition(new LatLng(Double.parseDouble(data.getQiangdan().getWeidu()), Double.parseDouble(data.getQiangdan().getJingdu())));
                            endList.clear();
                            endList.add(endLatlng);
                            clearRoute();
                            int strategyFlag = 0;
                            try {
                                strategyFlag = mAMapNavi.strategyConvert(true, true, true, false, true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (strategyFlag >= 0) {


                                mAMapNavi.calculateDriveRoute(startList, endList, wayList, strategyFlag);

                            }
                        }

                    }


                });
    }

    private void qiang_save() {
        EasyHttp.post(this)
                .api(new QiangSaveApi()
                        .setUid(SPUtil.get(this, IntentKey.UID, "")).setJingdu(longitude).setWeidu(latitude).setId(id))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode() == 200) {
                            btnQiangdan.setVisibility(View.GONE);
                            btnService.setVisibility(View.VISIBLE);
                            btnDestination.setVisibility(View.VISIBLE);
                        }

                    }


                });
    }


    @OnClick({R.id.tv_tophone, R.id.btn_qiangdan, R.id.btn_service, R.id.btn_destination, R.id.image_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tophone:
                Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));//跳转到拨号界面，同时传递电话号码
                startActivity(dialIntent);
                break;

            case R.id.btn_qiangdan:

//                qiang_save();
                break;
            case R.id.btn_service:
                break;
            case R.id.btn_destination:
                order_queren();
                break;
            case R.id.image_back:
                finish();
                break;

        }
    }

    private void order_queren() {
        EasyHttp.post(this)
                .api(new OrderQuerenApi()
                        .setUid(SPUtil.get(this, IntentKey.UID, "")).setId(id))
                .request(new HttpCallback<RegisterBean>(this) {

                    @Override
                    public void onSucceed(RegisterBean data) {
                        toast(data.getMessage());
                        if (data.getCode() == 200) {
                            finish();
                        }

                    }


                });
    }




    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation location) {
        if (location != null) {
            LatLng latLng = new LatLng(location.getCoord().getLatitude(),
                    location.getCoord().getLongitude());
            // 显示定位小图标，初始化时已经创建过了，这里修改位置即可
            mStartMarker.setPosition(latLng);
            if (isNeedFollow) {
                // 跟随
                mAmap.animateCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        } else {
            Toast.makeText(GrabbingDetailsActivity.this, "定位出现异常",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onGetNavigationText(String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteFailure(int arg0) {
        calculateSuccess = false;
        Toast.makeText(getApplicationContext(), "计算路线失败，errorcode＝" + arg0, Toast.LENGTH_SHORT).show();
    }




    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        //清空上次计算的路径列表。
        routeOverlays.clear();
        HashMap<Integer, AMapNaviPath> paths = mAMapNavi.getNaviPaths();
        for (int i = 0; i < ints.length; i++) {
            AMapNaviPath path = paths.get(ints[i]);
            if (path != null) {
                drawRoutes(ints[i], path);
            }
        }
        changeRoute();
    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {

    }

    @Override
    public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {

    }


    @Override
    public void onNaviRouteNotify(AMapNaviRouteNotifyData aMapNaviRouteNotifyData) {

    }

    @Override
    public void onGpsSignalWeak(boolean b) {

    }



    /**
     * 清除当前地图上算好的路线
     */
    private void clearRoute() {
        for (int i = 0; i < routeOverlays.size(); i++) {
            RouteOverLay routeOverlay = routeOverlays.valueAt(i);
            routeOverlay.setTrafficLine(true);
            routeOverlay.removeFromMap();
        }
        routeOverlays.clear();
    }
    private void drawRoutes(int routeId, AMapNaviPath path) {
        calculateSuccess = true;
        RouteOverLay routeOverLay = new RouteOverLay(mAmap, path, this);
        routeOverLay.setTrafficLine(true);
        routeOverLay.setStartPointBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.start));
        routeOverLay.setEndPointBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.end));
        routeOverLay.addToMap();
        routeOverLay.zoomToSpan(120);
        routeOverlays.put(routeId, routeOverLay);
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mRouteMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mRouteMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mRouteMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        startList.clear();
        wayList.clear();
        endList.clear();
        routeOverlays.clear();
        mRouteMapView.onDestroy();
        /**
         * 当前页面只是展示地图，activity销毁后不需要再回调导航的状态
         */
        mAMapNavi.removeAMapNaviListener(this);
        mAMapNavi.destroy();

    }

    @Override
    public void onPolylineClick(Polyline polyline) {

        if (routeOverlays != null && routeOverlays.size() == 1){
            return;
        }
        List<LatLng> latLngs = polyline.getPoints();
        if (latLngs.size() == 0){
            return;
        }
        LatLng latLng = latLngs.get(0);
        outer:
        for (int i = 0; i < routeOverlays.size(); i++) {
            int key = routeOverlays.keyAt(i);
            List<NaviLatLng> naviLatLngs = routeOverlays.get(key).getAMapNaviPath().getCoordList();
            for (NaviLatLng naviLatLng : naviLatLngs) {
                if (Math.abs((naviLatLng.getLatitude() - latLng.latitude)) <= 0.000000000001
                        && Math.abs((naviLatLng.getLongitude()- latLng.longitude)) <= 0.00000000001){
                    if (i == routeIndex){   // 已经选过该路线 跳转下一条路线 可能重复路线
                        continue outer;
                    }
                    for (int j = 0; j < routeOverlays.size(); j++) {
                        if (i == j){    //选中路线 不用画
                            continue;
                        }
                        int key2 = routeOverlays.keyAt(j);
                        routeOverlays.get(key2).setTransparency(0.4f);
                        routeOverlays.get(key2).setZindex(0);
                    }
                    routeOverlays.get(key).setTransparency(1.0f);
                    /**把用户选择的那条路的权值弄高，使路线高亮显示的同时，重合路段不会变的透明**/
                    routeOverlays.get(key).setZindex(1);
                    mAMapNavi.selectRouteId(key);
                    routeIndex = i;
                    chooseRouteSuccess = true;
                    return;
                }
            }
        }
    }
    public void changeRoute() {
        if (!calculateSuccess) {
            Toast.makeText(this, "请先算路", Toast.LENGTH_SHORT).show();
            return;
        }
        /**
         * 计算出来的路径只有一条
         */
        if (routeOverlays.size() == 1) {
            chooseRouteSuccess = true;
            mAMapNavi.selectRouteId(routeOverlays.keyAt(0));
            return;
        }
        if (routeIndex >= routeOverlays.size())
            routeIndex = 0;
        int routeID = routeOverlays.keyAt(routeIndex);
        for (int i = 0; i < routeOverlays.size(); i++) {
            int key = routeOverlays.keyAt(i);
            routeOverlays.get(key).setTransparency(0.4f);
            routeOverlays.get(key).setZindex(0);
        }
        routeOverlays.get(routeID).setTransparency(1);
        /**把用户选择的那条路的权值弄高，使路线高亮显示的同时，重合路段不会变的透明**/
        routeOverlays.get(routeID).setZindex(1);

        mAMapNavi.selectRouteId(routeID);
        routeIndex++;
        chooseRouteSuccess = true;

        /**选完路径后判断路线是否是限行路线**/
        AMapRestrictionInfo info = mAMapNavi.getNaviPath().getRestrictionInfo();
        if (!TextUtils.isEmpty(info.getRestrictionTitle())) {
            if (routeIndex == 0) {
                return;
            }
            changeRoute();
        }
    }
}
